<template>
  <div>
    <van-nav-bar
    title="登录"
    left-arrow
    @click-left="onClickLeft"
    />
    <h1 class="title">欢迎注册</h1>

    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="用户名"
        placeholder="请输入手机号"
        :rules="[{ required: true, pattern, message: '请输入正确手机号' }]"
        autocomplete="off"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, validator, message: '密码错误,最少6个字符'  }]"
        autocomplete="off"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="password"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, validator, message: '两次密码必须一致'  }]"
        autocomplete="off"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { registerAPI } from '@/api/user'
export default {
  name: 'LoginPage',
  data () {
    return {
      mobile: '',
      password: '',
      repassword: '',
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    }
  },
  methods: {
    onClickLeft () {
      this.$router.go(-1)
    },
    // 检验两次密码是否一致
    validator (val) {
      return (val === this.password && /^\S{6,}$/.test(val))
    },
    async onSubmit (values) {
      const { data } = await registerAPI(values)
      if (data.errno !== 0) {
        Toast(data.errmsg)
      } else {
        Toast('注册成功')
        this.mobile = this.password = this.repassword = ''
        localStorage.setItem('mobile-token-ydd', data.data.token)
        this.$router.push('/user')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #1989fa;
  // 导航文字
  /deep/ .van-nav-bar__title {
  color: white;
  font-weight: 500;
  font-size: 0.42667rem;
 }
  //修改箭头颜色
  /deep/ .van-icon-arrow-left {
  color: var(--nav-bar-icon-color, #fff) !important;
 }
}
.title {
  font-size: .8rem;
  color: #1989fa;
  font-weight: 400;
  text-align: center;
}
</style>
